package pl.edu.agh.ssm.monitor.utils;

import java.util.HashMap;

import pl.edu.agh.ssm.monitor.data.Packet;
import pl.edu.agh.ssm.monitor.data.Session;
import pl.edu.agh.ssm.monitor.data.SessionMedia;
import pl.edu.agh.ssm.monitor.listeners.PacketListener;
import pl.edu.agh.ssm.monitor.listeners.RTCPDataListener;
import pl.edu.agh.ssm.monitor.listeners.RTPDataListener;
import pl.edu.agh.ssm.monitor.listeners.RtpAVPMediaTypeInfoProvider;
import pl.edu.agh.ssm.monitor.net.PacketFilter;
import pl.edu.agh.ssm.monitor.net.PacketReceiver;

public class PacketListenersUtils {

	public void createRtpAndRTCPDataListeners(PacketListener parent, Session session, PacketReceiver receiver,
			int priority, String address, int port, Packet packet, HashMap<Integer, SessionMedia> rtpmap, String sourceAddress, int sourcePort) {
		/* Create and add RTP Data listener */
		RTPDataListener dataListener = new RTPDataListener(parent,
				session);
		dataListener.setPriority(priority);
		RtpAVPMediaTypeInfoProvider mediaTypeInfoProvider = new RtpAVPMediaTypeInfoProvider();
		if(rtpmap != null) {
			for(Integer key : rtpmap.keySet()) {
//				System.out.println("Add media type info: " + key);
				mediaTypeInfoProvider.addMediaTypeInfo(key, rtpmap.get(key));
			}
		}
		dataListener.setMediaTypeInfoProvider(mediaTypeInfoProvider);
		PacketFilter rtpFilter = new PacketFilter();
		rtpFilter.setAddress(address);
		rtpFilter.setPort(port);
		rtpFilter.setSourceAddress(sourceAddress);
		rtpFilter.setSourcePort(sourcePort);
//		System.out.println("Add rtp listener on address: " + rtpFilter.getAddress() + ", on port: " + rtpFilter.getHighPort() +
//				" with source: " + sourceAddress + ":" + sourcePort + " " + dataListener);
		
		receiver.addPacketListenerToSession(dataListener, rtpFilter, session.getId()); // rtp data
		
		/* Create and add RTCP Data listener */
		RTCPDataListener rtcpDataListener = new RTCPDataListener(
				parent, session);
		rtcpDataListener.setPriority(priority);
		PacketFilter rtcpFilter = new PacketFilter();
		rtcpFilter.setAddress(address);
		rtcpFilter.setPort(port + 1);
		rtcpFilter.setSourceAddress(sourceAddress);
		rtcpFilter.setSourcePort(sourcePort);
		
//		System.out.println("Add rtp listener on address: " + rtcpFilter.getAddress() + ", on port: " + rtcpFilter.getHighPort() +
//				" with source: " + sourceAddress + ":" + sourcePort + " " +rtcpDataListener);
		receiver.addPacketListenerToSession(rtcpDataListener, rtcpFilter, session.getId());
		if(packet != null) {
			rtcpDataListener.processPacket(packet); //first rtcp packet caught 
		}
	}
}
